package cre.tomcat7.ch05.valve;

import org.apache.catalina.Request;
import org.apache.catalina.Response;
import org.apache.catalina.Valve;
import org.apache.catalina.ValveContext;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @Author penglai
 * @Date 2017/1/27.
 */
public class HeaderLoggerValve implements Valve {
    public String getInfo() {
        return null;
    }

    public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException {
        valveContext.invokeNext(request, response);

        System.out.println("HeaderLoggerValve");
        ServletRequest servletRequest = request.getRequest();
        HttpServletRequest httpServletRequest = null;

        if (servletRequest instanceof HttpServletRequest) {
            httpServletRequest = (HttpServletRequest) servletRequest;
            Enumeration names = httpServletRequest.getHeaderNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                System.out.println(name+": "+httpServletRequest.getHeader(name));
            }

        } else {
            System.out.println("Not an HTTP Request");
        }
        System.out.println("---------------------");
    }
}
